package com.mima.minaserver.client;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;

public class MyClient {

	 private InetSocketAddress inetSocketAddress;  
     
	    private IoSession session;  
	      
	    private IoConnector connector;
	    
	    public MyClient(String host,int port){  
	          
	        inetSocketAddress=new InetSocketAddress(host,port);  
	          
	    }  

	 public static void main(String[] args) {  
         
		 	MyClient udpClient=new MyClient("172.20.10.4", 8989);  
	        udpClient.setConnector(new NioDatagramConnector());  
	        udpClient.getConnector().setHandler(new ClientIoHandler());  
	        IoConnector connector=udpClient.getConnector();  
	        connector.getFilterChain().addLast("codec",   
	                new ProtocolCodecFilter(  
	                        new TextLineCodecFactory(  
	                                Charset.forName("UTF-8"),   
	                                LineDelimiter.WINDOWS.getValue(),  
	                                LineDelimiter.WINDOWS.getValue())));  
	          
	        ConnectFuture connectFuture=connector.connect(udpClient.getInetSocketAddress());  
	        // 等待是否连接成功，相当于是转异步执行为同步执行。  
	        connectFuture.awaitUninterruptibly();  
	        //连接成功后获取会话对象。如果没有上面的等待，由于connect()方法是异步的，  
	        //connectFuture.getSession(),session可能会无法获取。  
	        udpClient.setSession(connectFuture.getSession());  
	        udpClient.getSession().write("2b4140dbc66f4ec7bfe4a42e82aa57cctest1234,test1234 ".getBytes());  
	          
	    }  
	 
	 public IoSession getSession() {  
	        return session;  
	    }  
	  
	    public void setSession(IoSession session) {  
	        this.session = session;  
	    }  
	  
	    public IoConnector getConnector() {  
	        return connector;  
	    }  
	  
	    public void setConnector(IoConnector connector) {  
	        this.connector = connector;  
	    }  
	  
	    public InetSocketAddress getInetSocketAddress() {  
	        return inetSocketAddress;  
	    }  
	  
	    public void setInetSocketAddress(InetSocketAddress inetSocketAddress) {  
	        this.inetSocketAddress = inetSocketAddress;  
	    }  
	      

}
